/**
 * 
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 *   
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 * 
 */
package org.jiopi.ibean.kernel.context.classloader;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.jiopi.ibean.kernel.KernelConstants;
import org.jiopi.ibean.kernel.context.ContextCentralConsoleKernel;
import org.jiopi.ibean.kernel.repository.Repository;
import org.jiopi.ibean.share.ShareUtil.FileUtil;

/**
 * 
 * Common Lib Class Loader Manager
 * <P>
 * Cache specified Common Lib Class Loader <br/>
 * </P>
 * 
 * @since 2010.5.30
 *
 */
public class CommonLibClassLoaderManager {
	
	private final Map<String,CommonLibClassLoader> commonLibClassLoaders = Collections.synchronizedMap(new HashMap<String,CommonLibClassLoader>());
	
	private final ContextCentralConsoleKernel ccck;
	public CommonLibClassLoaderManager(ContextCentralConsoleKernel ccck){
		this.ccck = ccck;
	}
	
	public CommonLibClassLoader getCommonLibClassLoader(String jarFileName){
		Repository.CommonJar commomJar = Repository.getCommonJarByFileName(jarFileName);
		if(commomJar!=null){
			String id = commomJar.poolName+"-"+commomJar.groupName;
			CommonLibClassLoader clcl = commonLibClassLoaders.get(id);
			if(clcl == null){
				synchronized("CommonLibClassLoaderManager"+id){
					clcl = commonLibClassLoaders.get(id);
					if(clcl == null){
						String contextDir = ccck.contextDir.getAbsolutePath();
						String commonDir = FileUtil.joinPath(contextDir,"common");
						String commonTempDir = FileUtil.joinPath(contextDir,KernelConstants.TMP_DIR,"common");
						clcl = new CommonLibClassLoader(ccck.contextClassLoader ,commomJar.poolName,commomJar.groupName,commonDir,commonTempDir);
						commonLibClassLoaders.put(id, clcl);
					}
				}
			}
			clcl.addJar(jarFileName, commomJar.jarURL);
			return clcl;
		}
		
		return null;
	}
}
